package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.mvp.home.MortgageApplyCovenant;
import com.chexiehui.jc.mvp.home.MortgageApplyPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.CodeCountDownTimer;
import com.chexiehui.jc.utils.SoftKeyboardFixerForFullscreen;
import com.kyleduo.switchbutton.SwitchButton;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 车辆抵押贷款
 */
public class MortgageApplyActivity extends BaseMvpActivity<MortgageApplyPresenter> implements MortgageApplyCovenant.View {
    @BindView(R.id.tv_quote_title)
    TextView tvQuoteTitle;
    @BindView(R.id.tv_quote)
    TextView tvQuote;
    @BindView(R.id.tv_quote_tip)
    TextView tvQuoteTip;
    @BindView(R.id.iv_car_image)
    ImageView ivCarImage;
    @BindView(R.id.et_person_name)
    EditText etPersonName;
    @BindView(R.id.tv_person_city)
    TextView tvPersonCity;
    @BindView(R.id.ll_choose_city)
    LinearLayout llChooseCity;
    @BindView(R.id.et_person_phone)
    EditText etPersonPhone;
    @BindView(R.id.et_person_code)
    EditText etPersonCode;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.tv_car_model)
    TextView tvCarModel;
    @BindView(R.id.ll_choose_car_model)
    LinearLayout llChooseCarModel;
    @BindView(R.id.sb_mortgage_toggle)
    SwitchButton sbMortgageToggle;
    @BindView(R.id.rl_mortgage)
    RelativeLayout rlMortgage;
    @BindView(R.id.tv_buy_time)
    TextView tvBuyTime;
    @BindView(R.id.ll_choose_Buy_time)
    LinearLayout llChooseBuyTime;
    @BindView(R.id.tv_service_phone)
    TextView tvServicePhone;
    @BindView(R.id.rtv_apply)
    RadiusTextView rtvApply;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;

    private CarInfo carChooseInfo;
    private String chooseCity = "";
    private TimePickerView pvBuyTimePicker;
    private SimpleDateFormat sdfYyyymmdd = new SimpleDateFormat("yyyy-MM-dd");
    private String selectButTime;
    private int mortgageState = 1;
    private String borrowingId;
    private CodeCountDownTimer phoneLoginTimer;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if(bundle != null) {
            borrowingId = bundle.getString("borrowingId");
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("车辆抵押贷款");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_mortgage_apply;
    }

    @Override
    protected void initView(Bundle var1) {
        SoftKeyboardFixerForFullscreen.assistActivity(this);
        sbMortgageToggle.setChecked(true);
        sbMortgageToggle.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mortgageState = isChecked ? 1 : 0;
        });
        rtvApply.setEnabled(false);
    }

    @OnClick({R.id.ll_choose_city, R.id.ll_choose_car_model, R.id.tv_get_code, R.id.rl_mortgage, R.id.ll_choose_Buy_time, R.id.rtv_apply, R.id.tv_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_city:
                startActivityForResult(ChooseCityActivity.class, 300);
                break;
            case R.id.ll_choose_car_model:
                startActivityForResult(ChooseCarModelActivity.class, 200);
                break;
            case R.id.tv_get_code:
                mvpPresenter.sendCode();
                break;
            case R.id.rl_mortgage:
                sbMortgageToggle.toggle();
                break;
            case R.id.ll_choose_Buy_time:
                showBuyTimeDialog();
                break;
            case R.id.rtv_apply:
                mvpPresenter.doApply();
                break;
            case R.id.tv_agreement:
                startActivity(WebActivity.class, new BundleBuilder().putString("url", Constants.YRL_CYHGRXXBHTK).create());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 200:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        CarSeriesInfo carSeriesInfo = (CarSeriesInfo) data.getSerializableExtra("seriesInfo");
                        carChooseInfo = (CarInfo) data.getSerializableExtra("carInfo");
                        if (carSeriesInfo != null && carChooseInfo != null) {
                            tvCarModel.setText(carSeriesInfo.getName() + " " + carChooseInfo.getName());
                        }
                    }
                }
                break;
            case 300:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        BaiDuLocationInfo locationInfo = (BaiDuLocationInfo) data.getSerializableExtra("entity");
                        if (locationInfo != null && !StringUtils.isTrimEmpty(locationInfo.getCity())) {
                            chooseCity = locationInfo.getCity();
                            tvPersonCity.setText(chooseCity);
                        }
                    }
                }
                break;
        }
    }

    private void showBuyTimeDialog() {
        if (pvBuyTimePicker == null) {
            Calendar startDate = Calendar.getInstance();
            startDate.setTime(new Date());
            Calendar selectedDate = Calendar.getInstance();
            if(StringUtils.isTrimEmpty(selectButTime)){
                selectedDate.setTime(new Date());
            }else{
                selectedDate.setTime(TimeUtils.string2Date(selectButTime, sdfYyyymmdd));
            }
            Calendar endDate = Calendar.getInstance();
            endDate.setTime(new Date());
            endDate.add(Calendar.YEAR, 1);
            pvBuyTimePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date startDate, View v) {//选中事件回调
                    selectButTime = TimeUtils.date2String(startDate, sdfYyyymmdd);
                    tvBuyTime.setText(selectButTime);
                }
            })
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setCancelText("取消")//取消按钮文字
                    .setSubmitText("确定")//确认按钮文字
                    .setContentTextSize(18)
                    .setDividerColor(ContextCompat.getColor(mContext, R.color.c_999999))
                    .setItemVisibleCount(9)
                    .setLineSpacingMultiplier(2.5f)
                    .setTitleColor(ContextCompat.getColor(mContext, R.color.c_666666))
                    .setTitleSize(20)//标题文字大小
                    .setTitleText("选择开始时间")//标题文字
                    .setTitleColor(ContextCompat.getColor(mContext, R.color.c_333333))//标题文字颜色
                    .setTitleBgColor(ContextCompat.getColor(mContext, R.color.colorWhite))
                    .setSubmitColor(ContextCompat.getColor(mContext, R.color.app_color))//确定按钮文字颜色
                    .setCancelColor(ContextCompat.getColor(mContext, R.color.c_333333))//取消按钮文字颜色
                    .setBgColor(ContextCompat.getColor(mContext, R.color.colorWhite))//滚轮背景颜色 Night mode
                    .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                    .setRangDate(startDate,endDate)//起始终止年月日设定
                    .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                    .isCyclic(false)//是否循环滚动
                    .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                    .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .isDialog(false)//是否显示为对话框样式
                    .build();
        }
        pvBuyTimePicker.show();
    }

    @Override
    protected MortgageApplyPresenter createPresenter() {
        return new MortgageApplyPresenter(this);
    }

    @Override
    public void onSendCodeSuccess(BaseModel<Object> successResult) {
        showToast(String.format(getStringSource(R.string.s_yzmyfs_tips_),
                etPersonPhone.getText().toString().trim()));
        if(phoneLoginTimer == null){
            phoneLoginTimer = new CodeCountDownTimer(tvGetCode, 60000, 1000);
        }
        phoneLoginTimer.start();
        rtvApply.setEnabled(true);
    }

    @Override
    public void onSendCodeFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
        rtvApply.setEnabled(false);
    }

    @Override
    public void onDoApplySuccess(BaseModel<Object> successResult) {
        showToast(successResult.getResultInfo());
        onBackPressed();
    }

    @Override
    public void onDoApplyFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public String getBorrowingId() {
        return borrowingId;
    }

    @Override
    public String getPersonName() {
        return etPersonName.getText().toString().trim();
    }

    @Override
    public String getPersonMobile() {
        return etPersonPhone.getText().toString().trim();
    }

    @Override
    public String getPhoneCode() {
        return etPersonCode.getText().toString().trim();
    }

    @Override
    public String getPersonCity() {
        return chooseCity;
    }

    @Override
    public String getCarModelId() {
        return carChooseInfo != null ? carChooseInfo.getId() : "";
    }

    @Override
    public int getMortgageState() {
        return mortgageState;
    }

    @Override
    public String getBuyTime() {
        return selectButTime;
    }
}
